import {CCard} from '@/components/card'
import DimensionModalContent from './components/modal/dimensionModalContent'
import {
  DimensionTargetContent,
  DimensionDashboard,
  DimensionTypeSelect
} from './components/templateIndicatorsComp'
import {CnNormalSpan} from '@/components/text'
import deepClone from '@/libs/deepClone'
import {PropType, reactive, toRefs, ref, defineComponent, watch, computed, onMounted} from 'vue'
import {ant_design_vue} from '@/libs/global/antDesignVue'
const {message} = ant_design_vue
const Mobanzhibiao = defineComponent({
  props: {
    pmGroupDimensionList: {
      type: Array as PropType<Evaluation.PmGroupDimension[]>,
      default: []
    },
    showAppointScore: {
      type: Boolean,
      default: true
    }
  },
  emits: {
    'update:pmGroupDimensionList': (data: Evaluation.PmGroupDimension[]): boolean => true
  },
  setup(props, {emit}) {
    let state = reactive<{
      addEvalutaionModalVisible: boolean
      editEvalutaionModalVisible: boolean
      editEvalutaionModalData: Evaluation.PmGroupDimension | undefined

      pmGroupDimensionTypeCode: PmGroupDimensionTypeCode
      pmGroupDimensionList: Evaluation.PmGroupDimension[]
    }>({
      addEvalutaionModalVisible: false,
      editEvalutaionModalVisible: false,
      pmGroupDimensionTypeCode: '0020',
      pmGroupDimensionList: [],
      editEvalutaionModalData: undefined
    })

    const dimensWeightCount = computed(() => {
      let countWeight = (eval(
        state.pmGroupDimensionList.map(item => item.pmGroupDimensionWeight).join('+')
      ) || 0) as number
      return countWeight
    })

    watch(
      () => state.editEvalutaionModalVisible,
      n => {
        if (!n) {
          state.editEvalutaionModalData = undefined
        }
      }
    )

    watch(
      () => props.pmGroupDimensionList,
      n => {
        console.log('接收的考核维度列表', n)
        state.pmGroupDimensionList = n
      },
      {
        immediate: true
      }
    )

    watch(
      () => state.pmGroupDimensionList,
      n => {
        console.log('考核维度列表内容变化', n)
        pmGroupDimensionSort()
      },
      {
        deep: true
      }
    )

    function pmGroupDimensionSort() {
      console.log('考核维度列表排序', state.pmGroupDimensionList)
      for (let i = 0; i < state.pmGroupDimensionList.length; i++) {
        if (state.pmGroupDimensionList[i].sort !== i) {
          state.pmGroupDimensionList[i].sort = i
        }
      }
      emit('update:pmGroupDimensionList', state.pmGroupDimensionList)
    }

    function checkPmGroupDimension(
      data: Evaluation.PmGroupDimension,
      type: 'add' | 'edit' = 'add',
      oldData?: Evaluation.PmGroupDimension
    ) {
      let weight = Number(data.pmGroupDimensionWeight)

      console.log('校验考核维度', data, weight, dimensWeightCount.value)

      // 判断是否输入维度权重
      if (!weight) {
        message.warning({
          content: '请输入维度权重'
        })
        return false
      }

      if (type === 'add') {
        // 判断新添加的维度的权重，加上之前的维度权重是否大于100
        if (weight + dimensWeightCount.value > 100) {
          message.warning({
            content: `考核维度总权重超出100%，目前维度权重剩余${100 - dimensWeightCount.value}%`
          })
          return false
        }
      } else if (type === 'edit' && oldData) {
        if (oldData.pmGroupDimensionWeight === undefined) {
          return false
        } else {
          // 判断新添加的维度的权重，加上之前的维度权重是否大于100
          if (weight + dimensWeightCount.value - oldData.pmGroupDimensionWeight > 100) {
            message.warning({
              content: `目前维度权重修改时,需要小于${oldData.pmGroupDimensionWeight}%`
            })
            return false
          }
        }
      }

      // 判断是否输入维度名称
      if (!data.pmGroupDimensionName) {
        message.warning({
          content: '请输入维度名称'
        })
        return false
      }

      return true
    }

    function addPmGroupDimension(data: Evaluation.PmGroupDimension) {
      console.log('添加考核维度', data, dimensWeightCount.value)

      if (!checkPmGroupDimension(data)) return

      state.pmGroupDimensionList.push(deepClone(data))
    }

    function editPmGroupDimension(data: Evaluation.PmGroupDimension) {
      console.log('修改考核维度', data)
      const targetIdx = state.pmGroupDimensionList.findIndex(item => item.sort === data.sort)

      if (!checkPmGroupDimension(data, 'edit', state.pmGroupDimensionList[targetIdx])) return

      state.pmGroupDimensionList.splice(targetIdx, 1, data)
    }

    function delPmGroupDimension(index: number) {
      console.log('删除考核维度', index)
      state.pmGroupDimensionList.splice(index, 1)
    }

    function handleIndexTypeClick(data: PmGroupDimensionTypeCode) {
      state.pmGroupDimensionTypeCode = data
      state.addEvalutaionModalVisible = true
    }

    function handleEditClick(data: Evaluation.PmGroupDimension) {
      console.log('点击修改维度，当前数据', data)
      state.editEvalutaionModalData = data
      state.editEvalutaionModalVisible = true
    }

    return () => (
      <CCard title='考核维度' class='mb-18 border-0'>
        {/* 维度列表 */}
        {state.pmGroupDimensionList.length ? (
          [
            state.pmGroupDimensionList.map((item, idx) => (
              <DimensionDashboard
                pmGroupDimension={item}
                onDelete={() => {
                  delPmGroupDimension(idx)
                }}
                onEdit={() => {
                  handleEditClick(item)
                }}
              >
                <DimensionTargetContent
                  v-model={[
                    state.pmGroupDimensionList[idx].pmGroupDimensionTargetList,
                    'pmGroupDimensionTargetList'
                  ]}
                  pmGroupDimension={item}
                  dimensIndex={idx}
                  showAppointScore={props.showAppointScore}
                ></DimensionTargetContent>
              </DimensionDashboard>
            )),
            // 添加维度按钮
            <div
              class='w-full h-40 rounded-4 flex items-center gap-x-8 border-1 border-infoLight mt-16 px-16 cursor-pointer'
              onClick={() => {
                state.addEvalutaionModalVisible = true
              }}
            >
              <i class='iconfont icon-jiahao1 text-16 text-info'></i>
              <CnNormalSpan class='text-16'>添加考核维度</CnNormalSpan>
            </div>
          ]
        ) : (
          // 添加维度按钮
          <DimensionTypeSelect onIndexClick={handleIndexTypeClick}></DimensionTypeSelect>
        )}

        {/* 添加维度弹窗 */}
        <a-modal
          class='custom-modal w-1/3'
          title='添加维度'
          v-model={[state.addEvalutaionModalVisible, 'visible']}
          footer={false}
        >
          <DimensionModalContent
            v-models={[[state.addEvalutaionModalVisible, 'visible']]}
            onConfirm={addPmGroupDimension}
            pmGroupDimensionTypeCode={state.pmGroupDimensionTypeCode}
          ></DimensionModalContent>
        </a-modal>

        {/* 修改维度弹窗 */}
        <a-modal
          class='custom-modal w-1/3'
          title='修改维度'
          v-model={[state.editEvalutaionModalVisible, 'visible']}
          footer={false}
        >
          <DimensionModalContent
            v-models={[[state.editEvalutaionModalVisible, 'visible']]}
            defaultPmGroupDimension={state.editEvalutaionModalData}
            onConfirm={editPmGroupDimension}
          ></DimensionModalContent>
        </a-modal>
      </CCard>
    )
  }
})

export default Mobanzhibiao
